package meterMonitor.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.HttpStatusCodeException;
import org.springframework.web.client.ResourceAccessException;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.Charset;
import java.util.List;

public class RestfulBaseUtils {

    final static Logger logger            = LoggerFactory.getLogger(RestfulBaseUtils.class);

	 /**
     * 普通 rest请求
     */
    public static RestTemplate restTemplate      = new RestTemplate();
    

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static HttpEntity buildJsonRequestEntity(String entityBody) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept-Charset", "utf-8");
        if (entityBody == null || entityBody.length() == 0) {
            // 错误处理
            logger.error("RestfullUtils:buildRequestEntity entitybody 为空 ！");
        }
        HttpEntity entity = new HttpEntity(entityBody, headers);
        return entity;
    }

    /**
     * 创建请求的entity，自定义头部分
     * 
     * @param entityBody
     * @param headers
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static HttpEntity buildRequestEntity(String entityBody, HttpHeaders headers) {

        if (null == entityBody) {
            // 错误处理
            logger.error("RestfullUtils:buildRequestEntity entitybody 为空 ！");
        }

        if (null == headers) {
            // 错误处理
            logger.error("RestfullUtils:buildRequestEntity headers 为空 ！");
        }
        else {
            headers.set("Accept-Charset", "utf-8");
        }

        HttpEntity entity = new HttpEntity(entityBody, headers);
        return entity;
    }

    /**
     * 设置charset utf8
     */
    public static void setRestfullCharSet() {
        List<HttpMessageConverter<?>> httpMessageConverters = restTemplate.getMessageConverters();
        httpMessageConverters.set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
    }

    /**
     * 调用restfull处理远程调用
     * 
     * @param url
     * @param entity
     * @return
     */
    @SuppressWarnings("rawtypes")
    public static String doPostRestfullRequest(String url, HttpEntity entity) {
        logger.info("RestfullUtils:doPostRestfullRequest begin...");

        setRestfullCharSet();

        if (entity == null || null == url) {
            // 错误处理
            logger.error("RestfullUtils:doPostRestfullRequest entity or url is null !");
        }

        String response = restTemplate.postForObject(url, entity, String.class);
        return response;
    }

    public static String doGetRestfullRequest(String url) {
        setRestfullCharSet();

        if (null == url) {
            // 错误处理
            logger.error("RestfullUtils:doGetRestfullRequest entity or url is null !");
            return "";
        }
        String response = "";
        try {
            logger.info("请求的参数为:" + url);
            response = restTemplate.getForObject(url, String.class);
            logger.info("响应为:" + response);
        }
        catch (RestClientException e) {
            logger.error("RestfullUtils:restHttpPost do reques ..url:" + url + "exception:" + e.getMessage());
            throw e;
        }
        return response;
    }
    
    

    /**
     * @throws Exception
     * restHttpPost(restful post请求)
     * @param url
     * @param request
     * @param clazz
     * @return
     * @return String
     * @exception
     */
    public static <T> T  restHttpPost(String url, Class<T> clazz, Object request) {
        if (null == url) {
            // 错误处理
            logger.error("RestfullUtils:restHttpPost entity or url is null !");
            return null;
        }
        String jsonObj = request==null?"":JacksonMapper.toJson(request);
        return restHttpPost(url,jsonObj,clazz);
    }

    /**
     * restHttpPost(restful post请求)
     * @param url
     * @param request
     * @param clazz
     * @return
     * @return String
     * @exception
     */
    public static <T> T restHttpPost(String url, String request,Class<T> clazz) {
        setRestfullCharSet();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Accept-Charset", "utf-8");

        HttpEntity<String> entity = new HttpEntity<String>(request, headers);
        T response = null;
        try {
            logger.info("请求的参数为:" + request);
            response = restTemplate.postForObject(url, entity, clazz);
            if(response == null) {
            	throw new BizException("接口调用失败!");
            }
        }
        catch (Exception e) {
            logger.error("RestfullUtils:restHttpPost do reques ..url:" + url + "exception:" + e.getMessage());
            throw new BizException(e.getMessage(),e);
        }finally {
            logger.info("返回信息为:" + response);
        }
        return response;
    }

    public static <T> ResponseEntity<String> exchange(String uri, HttpEntity<T> request, HttpMethod method) {
        ResponseEntity<String> response = null;
        try {
            logger.info("请求的地址为:" + uri);
            logger.info("请求的参数为:" + request);
            response = restTemplate.exchange(uri, method, request, String.class);
            logger.info("响应:" + response.toString());
        }
        catch (HttpStatusCodeException e) {
            logger.error("后台服务出错,错误异常为:" + e.getMessage(), e);
        }
        catch (ResourceAccessException e) {
            logger.error("连接超时," + e.getMessage(), e);

        }
        catch (Exception e) {
            logger.error("服务出错:" + e.getMessage(), e);
        }
        if (!uri.contains("foot")) {
            logger.info("返回信息为:" + response);
        }

        return response;
    }
    
    
    /**
     * @throws Exception
     * restHttpPostCloud(restful post请求)
     * @param url
     * @param request
     * @param clazz
     * @return
     * @return String
     * @exception
     */
    public static <T> T restHttpPostCloud(String url, Object request,Class<T> clazz,RestTemplate restTemplateCloud) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.set("Accept-Charset", "utf-8");
        if (null == url) {
            // 错误处理
            logger.error("RestfullUtils:restHttpPost entity or url is null !");
            return null;
        }

        String jsonObj = (request instanceof String) ? (String)request : JacksonMapper.toJson(request);
        HttpEntity<String> entity = new HttpEntity<String>(jsonObj, headers);

        T response = null;
        try {
            response = restTemplateCloud.postForObject(url, entity, clazz);
            if(response == null) {
            	throw new BizException("接口调用失败!");
            }
        }
        catch (Exception e) {
            logger.error("RestfullUtils:restHttpPost do reques ..url:" + url + "exception:" + e.getMessage());
            throw new BizException(e.getMessage(),e);
        }
        return response;
    }
    
    
}
